package com.atguigu.daijia.customer.service.impl;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.customer.client.CustomerInfoFeignClient;
import com.atguigu.daijia.customer.service.CustomerService;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerServiceImpl implements CustomerService {

    //注入远程调用接口
    @Autowired
    private CustomerInfoFeignClient customerInfoFeignClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String login(String code) {
        //1 拿着code进行远程调用，返回用户id
        Result<Long> loginResult = customerInfoFeignClient.login(code);

        //2 判断 如果失败返回错误提示
        Integer resultCode = loginResult.getCode();
        if (resultCode != 200) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        //3 获取远程调用返回用户id
        Long customerId = loginResult.getData();

        //4 判断id是否为空
        if (null == customerId) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        //5 生成token字符串
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        //6 把用户id放入redis，设置过期时间
        // key: token   value:customerId
//        stringRedisTemplate.opsForValue().set(token,customerId.toString(),30L, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token, customerId.toString(),
                RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
        //7 返回token
        return token;
    }

    /**
     * 获取登录用户信息
     * @param customerId
     * @return
     */
    @Override
    public CustomerLoginVo getCustomerLoginInfo(long customerId) {
        //1 根据 用户id 远程调用 customer-service
        Result<CustomerLoginVo> customerLoginInfoResult = customerInfoFeignClient.getCustomerLoginInfo(customerId);

        //2 判断返回值是否为200
        if(customerLoginInfoResult.getCode().intValue()!=200){
            throw new GuiguException(customerLoginInfoResult.getCode(), customerLoginInfoResult.getMessage());
        }

        //3 获取返回的数据
        CustomerLoginVo customerLoginVo = customerLoginInfoResult.getData();

        //4 判断返回数据是否为空
        if(customerLoginVo==null){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        //5 返回远程调用的返回值结果
        return customerLoginVo;
    }
}
